//
//  ZDBManager.m
//  NewProject
//
//  Created by Apple on 2018/7/10.
//  Copyright © 2018年 chenIos. All rights reserved.
//

#import "ZDBManager.h"
#import "NSString+Encryption.h"
#import <FMDB/FMDB.h>
#define DBQueue [ZDBManager DBManager]
@implementation ZDBManager
+ (FMDatabaseQueue *)DBManager{
    static FMDatabaseQueue *queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"z_wallet_db"];
        
        queue = [FMDatabaseQueue databaseQueueWithPath:path];
        [queue inDatabase:^(FMDatabase * _Nonnull db) {
            //创建表
            BOOL createTableResult=[db executeUpdate:@"CREATE TABLE IF NOT EXISTS z_wallet_info (address text,name text,password text,coin text,coinStr text,isSelected text,privateKey text)"];
            if (createTableResult) {
                ZWLog(@"创建表成功");
            }else{
                ZWLog(@"创建表失败");
            }
            
        }];
    });
    return queue;
}

+ (FMDatabase *)syncDB{
    static FMDatabase *db;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"z_wallet_db"];
        db = [FMDatabase databaseWithPath:path];
    });
    return db;
}

+ (void)createWallet:(NSString *)name password:(NSString *)password address:(NSString *)address privateKey:(NSString *)key complition:(void (^)(BOOL exist, BOOL addressExist, BOOL isfirst,BOOL))completionHandler
{
    [DBQueue inDatabase:^(FMDatabase * _Nonnull db) {
        NSString *qurey = [NSString stringWithFormat:@"SELECT * FROM z_wallet_info WHERE address = '%@'",address];
        FMResultSet *rs = [db executeQuery:qurey];
        int sum = 0;
        BOOL addressExist = NO;
        BOOL nameExist =  NO;
        BOOL isFirst = YES;
        BOOL createSuccess = NO;
        while ([rs next]) {
            sum++;
        }
        if (sum) {
            addressExist = YES;
        }
        
        qurey = [NSString stringWithFormat:@"SELECT * FROM z_wallet_info WHERE name = '%@'",name];
        rs = [db executeQuery:qurey];
         sum = 0;
        while ([rs next]) {
            sum++;
        }
        if (sum) {
            nameExist = YES;
        }
        NSInteger offset = 0;
        qurey = [NSString stringWithFormat:@"SELECT * FROM z_wallet_info LIMIT 10 OFFSET %ld",(long)offset];
        rs = [db executeQuery:qurey];
        sum = 0;
        while ([rs next]) {
            sum++;
        }
        if (sum) {
            isFirst = NO;
        }
        if (nameExist == NO && addressExist==NO) {// 地址 和名字都不重复
            
            NSString * privatekey = [key aes256_encrypt_encode];
            NSString * privatePassword = [password aes256_encrypt_encode];
            if (privatekey&&privatePassword) {//添加密码成功
                NSString *str = [NSString stringWithFormat:@"INSERT INTO z_wallet_info(address,name,password,isSelected,privateKey) VALUES('%@','%@','%@',%d,'%@')",address,name,privatePassword,isFirst,privatekey];
                BOOL is = [db executeUpdate:str];
                if (is) {//加入数据库成功
                    ZWLog(@"写入成功");
                    createSuccess = YES;
                }else
                {
//                    [ZKeyChain deletePasswordForKey:address];
//                    [ZKeyChain deletePrivateForKey:address];
                    ZWLog(@"写入失败");
                }
                
            }else
            {
//                [ZKeyChain deletePrivateForKey:address];
            }
        }else
        {
//             [ZKeyChain deletePrivateForKey:address];
        }
        
        completionHandler(nameExist,addressExist,isFirst,createSuccess);
    }];

}

+ (void)changePkCoin:(NSString *)address coin:(long long)coin coinString:(NSString *)coinStr{
    [DBQueue inDatabase:^(FMDatabase * _Nonnull db) {
        NSString *str = [NSString stringWithFormat:@"UPDATE z_wallet_info SET coin=%@ ,coinStr=%@ WHERE address='%@'",@(coin),coinStr,address];
       BOOL is = [db executeUpdate:str];
        if (is) {
            ZWLog(@"修改成功");
        }else
        {
            ZWLog(@"修改失败");
        }
        
    }];

}

+ (void)changeSelectedWallet:(NSString *)address completion:(void (^)(BOOL))completionHandler
{
    [DBQueue inDatabase:^(FMDatabase * _Nonnull db) {
        
        NSString *str = [NSString stringWithFormat:@"UPDATE z_wallet_info SET isSelected = %d",false];
        BOOL is = [db executeUpdate:str];
        if (is) {
            ZWLog(@"修改成功将所有改为未选中状态");
            NSString *str = [NSString stringWithFormat:@"UPDATE z_wallet_info SET isSelected = %d WHERE address='%@'",true,address];
            BOOL is = [db executeUpdate:str];
            if (is) {
                ZWLog(@"修改成功 将选中的修改为切换状态");
                completionHandler(YES);
            }else
            {
                completionHandler(NO);
                ZWLog(@"修改失败");
            }

        }else
        {
             completionHandler(NO);
            ZWLog(@"修改失败");
        }
        
    }];
//    [self queryWallets:0 completion:^(NSArray *wallets) {
//
//    }];
    
}

+ (void)queryWallets:(NSInteger)page completion:(void (^)(NSArray *))completionHandler
{
    [DBQueue inDatabase:^(FMDatabase * _Nonnull db) {
        NSInteger offset = page * 100;
        NSString *str = [NSString stringWithFormat:@"SELECT * FROM z_wallet_info LIMIT 100 OFFSET %ld",(long)offset];
        FMResultSet *rs = [db executeQuery:str];
        NSMutableArray *array = [NSMutableArray array];
        while ([rs next]) {
            NSString *address = [rs stringForColumn:@"address"];
            NSString *name = [rs stringForColumn:@"name"];
            NSString *password = [rs  stringForColumn:@"password"];
            NSString *privateKey = [rs stringForColumn:@"privateKey"];
            privateKey = [privateKey aes256_decrypt_decode];
            password = [password aes256_decrypt_decode];
            BOOL isSelected = [rs boolForColumn:@"isSelected"];
            NSMutableDictionary *dic =[ @{
                                  @"walletAdress":address,
                                  @"name":name,
                                  @"password":password,
                                  @"privateKey":privateKey,
                                  @"isSelected":@(isSelected)
                                  } mutableCopy];
         
            ZWLog(@"查询结果 %@",dic);
            [array addObject:dic];
        }
        completionHandler(array);
    }];
}


+ (void)qureySelectedWallet:(void (^)(NSDictionary *))completionHandler
{
    [DBQueue inDatabase:^(FMDatabase * _Nonnull db) {
//        NSInteger offset = page * 10;
        NSString *str = [NSString stringWithFormat:@"SELECT * FROM z_wallet_info WHERE isSelected =  %d",YES];
        FMResultSet *rs = [db executeQuery:str];
//        NSMutableArray *array = [NSMutableArray array];
        while ([rs next]) {
            NSString *address = [rs stringForColumn:@"address"];
            NSString *name = [rs stringForColumn:@"name"];
            NSString *password = [rs  stringForColumn:@"password"];
            NSString *privateKey = [rs stringForColumn:@"privateKey"];
            privateKey = [privateKey aes256_decrypt_decode];
            password = [password aes256_decrypt_decode];
            
            BOOL isSelected = [rs boolForColumn:@"isSelected"];
            NSMutableDictionary *dic =[ @{
                                          @"walletAdress":address,
                                          @"name":name,
                                          @"password":password,
                                          @"isSelected":@(isSelected),
                                          @"privateKey":privateKey
                                          } mutableCopy];
          
            if (completionHandler) {
                  completionHandler(dic);
            }
          
            ZWLog(@"查询选中钱包结果 %@",dic);
        }
//        completionHandler(array);
    }];
}


+ (void)qureyName:(NSString *)name completion:(void (^)(BOOL ))completionHandler{
    
    [DBQueue inDatabase:^(FMDatabase * _Nonnull db) {
        NSString *str = [NSString stringWithFormat:@"SELECT * FROM z_wallet_info WHERE name = '%@'",name];
        FMResultSet *rs = [db executeQuery:str];
        //        NSMutableArray *array = [NSMutableArray array];
        int sum = 0;
        while ([rs next]) {
            sum++;
            NSString *address = [rs stringForColumn:@"address"];
//            NSString *name = [rs stringForColumn:@"name"];
            ZWLog(@"存在重名地址%@",address);
        }
        if (sum) {
            completionHandler(YES);
        }else
        {
            completionHandler(NO);
        }
        //        completionHandler(array);
    }];
    
}



+ (void)deleteWallet:(NSString *)address completion:(void (^)(BOOL,BOOL))completionHandler
{
    [DBQueue inDatabase:^(FMDatabase * _Nonnull db) {
        NSString *str = [NSString stringWithFormat:@"DELETE FROM z_wallet_info WHERE address = '%@'",address];
        BOOL is = [db executeUpdate:str];
        BOOL sucess = NO;
        BOOL haswallet = NO;
        if (is) {
            ZWLog(@"删除成功");
//            [ZKeyChain deletePasswordForKey:address];
//            [ZKeyChain deletePrivateForKey:address];
            sucess = YES;
        }else
        {
            ZWLog(@"删除失败");
        }
        
        str = [NSString stringWithFormat:@"SELECT * FROM z_wallet_info WHERE isSelected =  %d",YES];
        FMResultSet *rs = [db executeQuery:str];
        int sum = 0;
        while ([rs next]) {
            sum++;
        }
        NSInteger offset = 0;
        str = [NSString stringWithFormat:@"SELECT * FROM z_wallet_info LIMIT 1 OFFSET %ld",(long)offset];
        rs = [db executeQuery:str];
        NSMutableArray *array = [NSMutableArray array];
        while ([rs next]) {
            NSString *address = [rs stringForColumn:@"address"];
            NSString *name = [rs stringForColumn:@"name"];
//            NSString *coin = [rs stringForColumn:@"coin"];
//            NSString *coinStr = [rs stringForColumn:@"coinStr"];
            
            NSString *password = [rs stringForColumn:@"password"];
            NSString *privateKey = [rs stringForColumn:@"privateKey"];
            privateKey = [privateKey aes256_decrypt_decode];
            password = [password aes256_decrypt_decode];
            BOOL isSelected = [rs boolForColumn:@"isSelected"];
            NSMutableDictionary *dic =[ @{
                                          @"walletAdress":address,
                                          @"name":name,
                                          @"password":password,
                                          @"privateKey":privateKey,
                                          @"isSelected":@(isSelected)
                                          } mutableCopy];
         
            ZWLog(@"查询结果 %@",dic);
            [array addObject:dic];
        }
        if (array.count) {
            haswallet = YES;
        }
        
        if (sum==0) {
            
            if (array.count) {
                NSDictionary *dic = [array firstObject];
                NSString *str = [NSString stringWithFormat:@"UPDATE z_wallet_info SET isSelected = %d WHERE address='%@'",true,dic[@"walletAdress"]];
                BOOL is = [db executeUpdate:str];
                if (is) {
                    ZWLog(@"修改成功 将选中的修改为切换状态");
                }else
                {
                    ZWLog(@"修改失败");
                }
            }
           

        }
        completionHandler(sucess,haswallet);
    }];
}

+ (void)changePassword:(NSString *)password wallet:(NSString *)address completion:(void (^)(BOOL))completionHandler{
    [DBQueue inDatabase:^(FMDatabase * _Nonnull db) {
        
        NSString *passwordPrivate = [password aes256_encrypt_encode];
        BOOL is;
        if (passwordPrivate) {
            NSString *str = [NSString stringWithFormat:@"UPDATE z_wallet_info SET password = '%@' WHERE address = '%@'",passwordPrivate,address];
            is = [db executeUpdate:str];
            if (is) {
                ZWLog(@"密码修成功")
            }else
            {
                ZWLog(@"密码修改失败")
            }
        }else
        {
            is = NO;
        }
       
        if (completionHandler) {
            completionHandler(is);
        }
        
    }];
}


+ (void)queryPassword:(NSString *)address completion:(void (^)(NSString *))completionHandler
{
    
    [DBQueue inDatabase:^(FMDatabase * _Nonnull db) {
        NSString *str = [NSString stringWithFormat:@"SELECT * FROM z_wallet_info WHERE address = '%@'",address];
        FMResultSet *rs = [db executeQuery:str];
        //        NSMutableArray *array = [NSMutableArray array];
        int sum = 0;
        NSString *password = nil;
        while ([rs next]) {
            sum++;
            password = [rs stringForColumn:@"password"];
            password = [password aes256_decrypt_decode];
            //            NSString *name = [rs stringForColumn:@"name"];
            ZWLog(@"password = %@",password);
        }
        if (completionHandler) {
            completionHandler(password);
        }
       
    }];
    
}
+ (void)queryPrivateKey:(NSString *)address completion:(void (^)(NSString *))completionHandler
{
    
    [DBQueue inDatabase:^(FMDatabase * _Nonnull db) {
        NSString *str = [NSString stringWithFormat:@"SELECT * FROM z_wallet_info WHERE address = '%@'",address];
        FMResultSet *rs = [db executeQuery:str];
        //        NSMutableArray *array = [NSMutableArray array];
        int sum = 0;
        NSString *privateKey = nil;
        while ([rs next]) {
            sum++;
            privateKey = [rs stringForColumn:@"privateKey"];
            privateKey = [privateKey aes256_decrypt_decode];
            //            NSString *name = [rs stringForColumn:@"name"];
            ZWLog(@"password = %@",privateKey);
        }
        if (completionHandler) {
            completionHandler(privateKey);
        }
        
    }];
    
}















@end
